from flask import Flask, render_template, request, redirect, url_for
from flask_login import LoginManager, login_user
from flask_wtf import FlaskForm
from werkzeug.security import generate_password_hash
import uuid
from flask_login import UserMixin  # 引入用户基类
from werkzeug.security import check_password_hash
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, EqualTo
from app import app

from . import *
from .models import User

login_manager = LoginManager()  # 实例化登录管理对象
login_manager.init_app(app)  # 初始化应用
login_manager.login_view = 'login'  # 设置用户登录视图函数 endpoint

def get_user(user_name):
    """根据用户名获得用户记录"""
    user = User
    user_info = user.query.filter_by(username=user_name).first()
    if user_info is not None:
        return user_info
    return None

class Users(UserMixin):
    """用户类"""
    def __init__(self, user):
        self.username = user.get("username")
        self.password_hash = user.get("password")
        self.id = user.get("id")

    def verify_password(self, password):
        """密码验证"""
        print("password:", password, "password_hash:", self.password_hash)
        print(check_password_hash(self.password_hash, password))
        if self.password_hash is None:
            return False

        return self.password_hash == password

    def get_id(self):
        """获取用户ID"""
        return self.id

    @staticmethod
    def get(user_id):
        """根据用户ID获取用户实体，为 login_user 方法提供支持"""
        if not user_id:
            return None
        for user in User.query.all():
            if user.get('id') == user_id:
                return User(user)
        return None

@login_manager.user_loader  # 定义获取登录用户的方法
def load_user(user_id):
    return Users.get(user_id)

class LoginForm(FlaskForm):
    """登录表单类"""
    username = StringField('用户名', validators=[DataRequired()])
    password = PasswordField('密码', validators=[DataRequired()])


@admin.route('/login/', methods=('GET', 'POST'))  # 登录
def login():
    form = LoginForm()
    emsg = None
    if form.validate_on_submit():
        user_name = form.username.data
        password = form.password.data
        user_info = get_user(user_name)  # 从用户数据中查找用户记录
        if user_info is None:
            print(11111111111111111111111111111111111111)
            emsg = "用户名或密码密码有误"
        else:
            user = Users(user_info)  # 创建用户实体
            print(user.verify_password(password))
            if user.verify_password(password):  # 校验密码
                print(1111111111111111)
                # login_user(user)  # 创建用户 Session
                return redirect(request.args.get('next') or url_for('admin.indexss'))
            else:
                emsg = "用户名或密码密码有误"
    return render_template('login.html', form=form, emsg=emsg)
@admin.route('/indexss', methods=('GET', 'POST'))  # 登录
def indexss():
    return "成功登录"

if __name__ == '__main__':
    app.run()